package weaver.filter;



import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.validation.Assertion;
import weaver.common.util.string.StringUtil;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.integration.util.SessionUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

public class AuthLoginFilter implements Filter {
    private static Log log = LogFactory.getLog(AuthLoginFilter.class);

    /**
     * 排除路径，多个用|分隔
     */
    private String excludePath;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        excludePath = filterConfig.getInitParameter("excludePath");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //log.info("isNeedExclude(req)==" + isNeedExclude(req));
        BaseBean bb = new BaseBean();
        User user = (User) req.getSession(true).getAttribute("weaver_user@bean");
        //是否需要排除路径
        if (isNeedExclude(req)) {
            filterChain.doFilter(req, resp);
            return;
        }

        //  SessionUtil.createSession("7413", req, resp);


        log.info("进入拦截器user=="+user);

        String currentPage = req.getServletPath().toLowerCase();
        //用户已登录时
        if (user != null) {
           // log.info("当前页面dagnqianyemian==" + currentPage);
            String tourl = SessionUtil.getHomePageAfterLogin(req, resp);
          //  log.info("当前获取地址 dangqianhuoqudizhi==" + tourl);
            if (tourl.indexOf("/wui/index.html#/main") > -1){
                filterChain.doFilter(req, resp);
            }else if (StringUtil.isNotNullAndEmpty(tourl)) {
                resp.sendRedirect(tourl);
            }else {
                filterChain.doFilter(req, resp);
            }
            return;
        } else {  //未登录则跳转到统一认证页面
            String SSOLoginName="";
            Map<String,Object> arr;
            //在跳转平台登录页前，校验平台校验接口是否正常，正常跳转至sso登陆页面，否则跳转OA登录页 todo
            Assertion assertion = (Assertion) req.getSession().getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
            bb.writeLog("进入测试11"+assertion);
            Assertion assertion1 = (Assertion) req.getSession(true).getAttribute("_const_cas_assertion_");
            bb.writeLog("进入测试2"+assertion);
            Map attributes = assertion.getAttributes();
            bb.writeLog("进入测试3"+attributes);
//            for(Object key : attributes.keySet()){
//                Object value = attributes.get(key);
//                bb.writeLog("map值:"+key+"  "+value);
//            }
//            String workcode=(String) attributes.get("workcode");
//
//            bb.writeLog("进入测试workcode"+workcode);
//            String emamil = (String) attributes.get("email");
//            bb.writeLog("进入测试emamil4"+emamil);


            AttributePrincipal principal = assertion.getPrincipal();

            arr=principal.getAttributes();

            String emamil = (String) arr.get("email");
            bb.writeLog("进入测试emamil4"+emamil);
            SSOLoginName = principal.getName();
            SessionUtil.createSession("14087", req, resp);
            String tourl = "/wui/index.html#/main";
            resp.sendRedirect(tourl);

            return;

        }
    }

    @Override
    public void destroy() {

    }
    /**
     * 是否排除路径
     *
     * @return
     */
    private boolean isNeedExclude(HttpServletRequest request) {
        boolean result = false;
        //OALogin后门登录
        HttpSession session = request.getSession();
        String OAloginType = (String) request.getSession(false).getAttribute("weaver_login_type");
//        log.info("OAloginType=="+OAloginType);
        if (OAloginType != null) {
            //OA里的用户
            User user = (User) request.getSession(false).getAttribute("weaver_user@bean");
            if (OAloginType.equals("OALogin") && user != null) {
                return true;
            }
        }
        //当前页面
        String currentPage = request.getServletPath();
        //log.info("currentPage==" + currentPage);
        //当前是统一认证的登录页,跳转结束
        String queryString = request.getQueryString();
        if (currentPage.indexOf("/login/Login.jsp") == 0 && queryString != null && queryString.indexOf("appid") > -1 && queryString.indexOf("service") > -1) {
            return true;
        }
        //根据配置的页面判断前面页面是否在排除页面中
        String excludes[] = this.excludePath.replace("\r", "").replace("\n", "").replaceAll(" ", "").replace("\t", "").split("[|]");
        for (int i = 0; i < excludes.length; i++) {
            if (currentPage.indexOf(excludes[i]) == 0) {
                String exclude = request.getHeader("exclude");
                if ("workflowtodoc".equals(exclude)) {
                    request.getSession(true).setAttribute("weaver_login_type", "OALogin");
                }
                result = true;
                break;
            }
        }
        //判断当前页面是否是指定的sysadmin登录页面
        if (currentPage.equalsIgnoreCase("/login/OALogin.jsp")) {
            result = true;
        }
        //判断来源页面是否是指定的sysadmin登录页面
        String referer = request.getHeader("referer");
        if (referer != null) {
            if (referer.indexOf("/login/OALogin.jsp") > -1) {
                result = true;
            }
        }
        //判断是否是原OA的登录方式或者emessage登录
        String weaver_login_type = (String) request.getSession(true).getAttribute("weaver_login_type");
//        log.info("weaver_login_type=="+weaver_login_type);
        if (weaver_login_type != null) {
            if (weaver_login_type.equals("emessage") || weaver_login_type.equals("OALogin")) {
                result = true;
            }
        }
        //判断当前页面是否是OA登录页面
        if (currentPage.equalsIgnoreCase("/login/Login.jsp")) {
            request.getSession(true).removeAttribute("weaver_login_type");
            result = false;
        }
        String requestSource = Util.null2String(request.getParameter("em_client_type"));
        //log.info("testType=" + requestSource);
        //如果当前路径来自于移动端
        //log.info("mobile==" + (currentPage.indexOf("mobile") != -1));
        if (((currentPage.toLowerCase()).indexOf("mobile") != -1) || "mobile".equals(requestSource)) {
            result = true;
        }
        return result;
    }
}
